package com.plian.system.controller.dsh;

import cn.hutool.core.util.DesensitizedUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.plian.Tools.*;
import com.plian.Tools.base.BaseController;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.annotation.LogOperation;
import com.plian.system.common.status.CustomCode;
import com.plian.system.config.Resubmit;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.dto.dsh.DshStaffManagementDTO;
import com.plian.system.entity.dsh.DshStaffManagement;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.search.TokenSearch;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.service.dsh.IDshStaffManagementService;
import com.plian.system.service.hr.staff.IStaffFilesService;
import com.plian.system.vo.dsh.DshStaffManagementVO;
import com.plian.system.vo.hr.staff.StaffFilesVO;
import com.plian.system.vo.report.ReportReturnVO;
import com.plian.system.wrapper.dsh.DshStaffManagementWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Optional;

/**
 * @description:董事会
 * @author: z
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("api/dsh")
public class DshStaffManagementController extends BaseController {

    private IDshStaffManagementService dshStaffManagementService;

    private IStaffFilesService staffFilesService;

    private DshStaffManagementWrapper dshStaffManagementWrapper;

    /**
     * 详情
     */
    @PostMapping("/detail")
    public R<DshStaffManagementVO> detail(@Valid @RequestBody DshStaffManagement supervisor) {
        DshStaffManagement detail = dshStaffManagementService.getOne(Condition.getQueryWrapper(supervisor));
        DshStaffManagementVO supervisorVO = dshStaffManagementWrapper.entityToVO(detail);
        return dshStaffManagementService.getDetailObj(supervisorVO);
    }

    /**
     * 详情接口（数据脱敏）
     * @param staffFiles
     * @return
     */
    @PostMapping("/dataMaskingDetail")
    public R<DshStaffManagementVO> dataMaskingDetail(@Valid @RequestBody DshStaffManagement staffFiles) {
        R<DshStaffManagementVO> r = this.detail(staffFiles);
        // 脱敏处理
        if (r != null && r.getPageData() != null) {
            DshStaffManagementVO dshVO = r.getPageData();
            StaffFilesVO vo = dshVO.getStaffFilesVO();
            if(vo != null){
                vo.setDocumentNumber(DesensitizedUtil.desensitized(vo.getDocumentNumber(), DesensitizedUtil.DesensitizedType.ID_CARD));
                vo.setPlaceOfDomicile(DesensitizedUtil.desensitized(vo.getPlaceOfDomicile(), DesensitizedUtil.DesensitizedType.ADDRESS));
                vo.setTelephone(DesensitizedUtil.desensitized(vo.getTelephone(), DesensitizedUtil.DesensitizedType.MOBILE_PHONE));
                vo.setEmail(DesensitizedUtil.desensitized(vo.getEmail(), DesensitizedUtil.DesensitizedType.EMAIL));
                vo.setWorkPhone(DesensitizedUtil.desensitized(vo.getWorkPhone(), DesensitizedUtil.DesensitizedType.FIXED_PHONE));
                vo.setFamilyAddress(DesensitizedUtil.desensitized(vo.getFamilyAddress(), DesensitizedUtil.DesensitizedType.ADDRESS));
                vo.setEmergencyContactUs(DesensitizedUtil.desensitized(vo.getEmergencyContactUs(), DesensitizedUtil.DesensitizedType.MOBILE_PHONE));
                dshVO.setStaffFilesVO(vo);
            }
            r.setPageData(dshVO);
        }
        return r;
    }

    /**
     * 分页 监事会
     */
    @PostMapping("/list")
    public ListResult<DshStaffManagementVO> list(@Valid @RequestBody Query query) {
        if(query.getAscs()==null&&query.getDescs()==null){
//            query.setAscs("supervisor_position_id");
            query.setDescs("create_time");
        }

        List<SearchEntity> entityList = query.getSearch();
        QueryWrapper<DshStaffManagement> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new DshStaffManagement()), entityList
        );

        TokenSearch<DshStaffManagement> tokenSearch = new TokenSearch<>();
        if(null == query.getFlag()) query.setFlag(1);
        tokenSearch.addTokenQuery(queryWrapper, query);
//        queryWrapper.eq("create_company_id", TokenUtil.getTokenOrgId());

        IPage<DshStaffManagement> pages = dshStaffManagementService.page(Condition.getPage(query), queryWrapper);
        List<DshStaffManagementVO> supervisorVOS = dshStaffManagementWrapper.entityToVO(pages.getRecords());
        ListResult<DshStaffManagementVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(supervisorVOS);
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
        return listResult;

    }

    /**
     * 新增或修改 监事会
     */
    @PostMapping("/submit")
    @Resubmit(delaySeconds = 0)
    @LogOperation("董事会档案-提交")
    public R submit(@Valid @RequestBody DshStaffManagement supervisor) {
        String checkResult = "";
        StaffFilesVO staffFilesVO = supervisor.getStaffFilesVO();
        if (!(Optional.ofNullable(staffFilesVO.getStatus()).isPresent() && staffFilesVO.getStatus() == FormStatusConstant.STASH)){
            checkResult = staffFilesService.checkIsExisted(staffFilesVO.getId(),staffFilesVO.getStaffCode(),staffFilesVO.getCompanyNameId());
        }

        if(StringUtil.isBlank(checkResult)) {
            if (!staffFilesService.checkDocumentNumber(staffFilesVO.getId(), staffFilesVO.getCompanyNameId(), staffFilesVO.getDocumentNumber())) {
                return new R(CustomCode.builder().message("证件号已存在").code(1999).success(false).build());
            }
        }
        return dshStaffManagementService.submit(supervisor);
    }


    /**
     * 删除 监事会
     */
    @PostMapping("/remove")
    @LogOperation("董事会档案-删除")
    public R remove(@RequestBody PageData pd) {
        List<String> ids = (List<String>)pd.get("ids");
        return dshStaffManagementService.deleteLogic(Func.toLongList(StringUtils.join(ids, StringPool.COMMA)))
                ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
    }

    /**
     *
     * @param supervisorDTO
     * @return
     */
    @PostMapping("/report")
    public ObjResult reportTable(@RequestBody DshStaffManagementDTO supervisorDTO) {
        ReportReturnVO reportReturnVO = dshStaffManagementService.report(supervisorDTO);
        ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
        if (Optional.ofNullable(reportReturnVO).isPresent()){
            PageData pd = new PageData();
            pd.put("grids", reportReturnVO.getGrids());
            objResult.setPageData(pd);
        }
        return objResult;

    }

    /**
     * 新增导入(导入时仅导入系统内编码不存在的数据)
     */
    @PostMapping("/excelImport")
    @LogOperation("董事会档案-导入")
    public ObjResult excelImport(@RequestParam("file") MultipartFile multipartFile) throws IOException {
        String progressId = TokenUtil.getTokenUserId() + "_" + System.currentTimeMillis();
        CacheUtil.put("progress", "progress", progressId + "#half:hour", 0);
        InputStream inputStream = multipartFile.getInputStream();
        dshStaffManagementService.importExcel(progressId, inputStream, false);
        ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
        PageData pd = new PageData();
        pd.put("progressId", progressId);
        objResult.setPageData(pd);
        return objResult;
    }

    /**
     * 覆盖导入(导入时仅导入系统内编码存在的数据)
     */
    @PostMapping("/excelCoverImport")
    @LogOperation("董事会档案-导入")
    public ObjResult excelCoverImport(@RequestParam("file") MultipartFile multipartFile) throws IOException {
        String progressId = TokenUtil.getTokenUserId() + "_" + System.currentTimeMillis();
        CacheUtil.put("progress", "progress", progressId + "#half:hour", 0);
        InputStream inputStream = multipartFile.getInputStream();
        dshStaffManagementService.importExcel(progressId, inputStream, true);
        ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
        PageData pd = new PageData();
        pd.put("progressId", progressId);
        objResult.setPageData(pd);
        return objResult;
    }

    @GetMapping("/exportTemplateExcel")
    public void exportTemplateExcel(HttpServletResponse response, OutputStream os) {
        dshStaffManagementService.exportTemplateExcel(response, os);
    }

    /**
     * 生成可以导入的excel文件
     *
     * @return
     */
    @GetMapping("/exportImportFile")
    public ObjResult exportImportFile() {
        PageData pd = new PageData();
        pd.put("key", dshStaffManagementService.exportImportFile());
        ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
        objResult.setPageData(pd);
        return objResult;
    }

    /**
     * 下载excel文件 并删除
     *
     * @param key
     * @param response
     */
    @GetMapping("/download/{key}")
//    @PassToken
    public void download(@PathVariable String key, HttpServletResponse response) {
        dshStaffManagementService.download(key, response);
    }

    @GetMapping("/progress/{progressId}")
    public ObjResult progress(@PathVariable String progressId) {
        Object data = CacheUtil.get("progress", "progress", progressId + "#half:hour");
        if (data != null && data instanceof String) {
            if ("导入成功".equals(data)) {
                ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
                PageData pd = new PageData();
                pd.put("data", 200);
                objResult.setPageData(pd);
                return objResult;
            }
            return new ObjResult(CustomCode.builder().message((String) data).code(1000).success(false).build());
        }
        ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
        PageData pd = new PageData();
        pd.put("data", data);
        objResult.setPageData(pd);
        return objResult;
    }

}
